#!/usr/bin/python
# -*- coding: utf-8 -*-

""" 一個奇數值的 iterator """

# Excerpt from Python reference:
# https://docs.python.org/2/library/stdtypes.html#iterator-types
#
# One method needs to be defined for container objects to provide iteration support:
#
# container.__iter__()
#     Return an iterator object. The object is required to support the iterator protocol
#     described below.
#
# The iterator objects themselves are required to support the following two methods, which
# together form the iterator protocol:
#
# iterator.__iter__()
#     Return the iterator object itself.
#     This is required to allow both containers and iterators to be used with the for and
#     in statements.
# iterator.next()
#     Return the next item from the container.
#     If there are no further items, raise the StopIteration exception.


class OddContainer(object):
	""" 奇數容器 """

	def __init__(self, bound_value, *args, **kwds):
		super(OddContainer, self).__init__(*args, **kwds)

		self.bound_value = bound_value

		print "creating OddContainer with boundary=%r" % (bound_value,)
	# ### def __init__

	def __iter__(self):
		# 實作 container.__iter__()
		print "OddContainer.__iter__()"
		return OddIterator(self.bound_value)
	# ### def __iter__
# ### class OddContainer


class OddIterator(object):
	""" 奇數迭代器 """

	def __init__(self, bound_value, *args, **kwds):
		super(OddIterator, self).__init__(*args, **kwds)

		self.current_value = 1
		self.bound_value = bound_value

		print "creating OddIterator with boundary=%r" % (bound_value,)
	# ### def __init__

	def __iter__(self):
		# 實作 iterator.__iter__()
		return self
	# ### def __iter__

	def next(self):
		# 實作 iterator.next()
		aux = self.current_value + 2

		if aux > self.bound_value:
			print "OddIterator.next(): current=%r, boundary=%r; StopIteration()" % (self.current_value, self.bound_value,)
			raise StopIteration()

		print "OddIterator.next(): current=%r=>%r, boundary=%r; return %r" % (self.current_value, aux, self.bound_value, aux,)
		self.current_value = aux
		return aux
	# ### def next
# ### class OddIterator



o = OddContainer(9)
for v in o:
	print "v: %r" % (v,)



# vim: ts=4 sw=4 foldmethod=marker ai nowrap
